import { getDayBillCode, getSaveDaySettlementBill } from "@src/mainSystem/generate"
import { getDomCookies } from "../../utils/common"
import { getCookieValByKey } from "@src/utils/common"
import { DomMessageInstance } from "../../utils/DomMessage"
import { priviateAccount, userUnitid } from "@src/config/accountInfo"

export const useSpecificData = () => {
  const validatePage = () => {
    const domlist = document.querySelectorAll('.el-breadcrumb__inner'); 
    if(!domlist?.length) return false
    const dom:any = domlist?.[domlist.length -1]
    return dom.innerText === '日清算单查询'
  }

  const getDate = () => {
    const topDom = document?.querySelectorAll('iframe')[1]?.contentDocument || document
    const dom:any = topDom?.querySelector('.el-date-editor--month')?.querySelector('.el-input__inner')
    return dom?.value || undefined
  }

/** 点击页面中 获取数据 按钮时触发的方法 */
  const getData = async () => {
    console.log('getData 日账单')
    if(!validatePage()) return DomMessageInstance.error({content:'只能在 日清算单查询 使用此按钮'})
    if(!getDayBillCode()) return DomMessageInstance.error({content:'此账号未配置 账号 对应的 日账单code !'})
    
    try {
      const Cookie = getDomCookies() as string
      const tag = getCookieValByKey(Cookie, 'ClientTag=')
      const tick = getCookieValByKey(Cookie, 'Admin-Token=')
      const xToken = getCookieValByKey(Cookie, 'X-Token=')
      // XHXT_SESSIONID
      const headers = {
        Cookie,'X-Ticket':tick, 'Clienttag':tag, 'X-Token':xToken,
        Accept: `application/json, text/plain, */*`,
        'Content-Type': `application/json;charset=UTF-8`,
        // Currentroute: `/pxf-settlement-extnet/statementConfirm-SD?billsType=D1`
      }
      let userInfo:any = window.sessionStorage.getItem('KUANGJIAZU-PXF-COMMON-PORTAL-SESSION-userInfo-')
      userInfo = userInfo && JSON.parse(userInfo)
      let unitid = userUnitid?.[userInfo?.userName] || ''
      if(unitid !== userUnitid[priviateAccount])  {
        DomMessageInstance.error({content:`此用户不能获取日账单私有数据 ${unitid}`})
        return Promise.resolve()
      }
      getSaveDaySettlementBill({headers, userInfo, certainDate: getDate()})
    }catch(e) {
      console.error(e)
    }
  }

  return {
    getData
  }
}